package com.ews.onlineexchange.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.enterprise.inject.Model;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.criteria.*;

import com.ews.onlineexchange.model.*;
import com.ews.onlineexchange.service.UserService;
import org.apache.commons.lang3.StringUtils;

import com.ews.onlineexchange.controller.pub.QualificationConditionBean;
import com.ews.onlineexchange.service.EntityQuery;
import org.apache.lucene.search.Sort;

@Model
public class ServiceSupplierManageList extends EntityQuery<ServiceSupplier> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Inject
	QualificationConditionBean conditionBean;
	private String seqNo;
	private String cnname; //待定名单中，过滤中介使用
	private BigDecimal minScore;
	private BigDecimal maxScore;
	private
	@Inject
	EntityManager entityManager;
	@Inject
	UserService userService;
	public ServiceSupplierManageList() {
//		setOrder("auditted DESC,creditScore DESC,createDate DESC");
//		setOrder("lastUpdateDate desc  ");
		setMaxResults(MAX_RESULTS_NORMAL);
	}
	
	@Override
	protected List<Predicate> getRestrictions(CriteriaBuilder cb, Root<ServiceSupplier> entity) {
		List<Predicate> restrictions = new ArrayList<Predicate>();
//		restrictions.add(cb.isNull(entity.get("auditted")));		
		restrictions.add(cb.equal(entity.get("delFlag"),DataEntity.DEL_FLAG_NORMAL));
		User user = userService.getLoginedUser();
		if(user != null){
			String userRegion = user.getRegion();
//			if("370501".equals(userRegion))restrictions.add(cb.or(cb.equal(entity.get("region"), user.getRegion()),cb.equal(entity.get("region"),"000000")));
//			else restrictions.add(cb.equal(entity.get("region"), user.getRegion()));
			if(!"370501".equals(userRegion))restrictions.add(cb.equal(entity.get("region"), user.getRegion()));
		}
		if(StringUtils.isNotBlank(getRegion())){
			restrictions.add(cb.equal(entity.get("region"), getRegion()));
		}
		String supplierName = (String)getParameterValues().get("supplierName");
		if (!StringUtils.isBlank(supplierName))
			restrictions.add(cb.like(entity.get("cnname"), getStringRestriction(supplierName)));
		String auditStatus = (String)getParameterValues().get("auditStatus");
		if(StringUtils.isNoneBlank(auditStatus)) {
			if("2".equals(auditStatus)) {
				restrictions.add(cb.isNull(entity.get("auditted")));
				setOrder("createDate desc nulls last");
			}else if ("0".equals(auditStatus)) {
				restrictions.add(cb.isFalse(entity.<Boolean>get("auditted")));
				setOrder("auditDate desc ");
			}else {
				restrictions.add(cb.isTrue(entity.<Boolean>get("auditted")));
				setOrder("auditDate desc ");
			}
		}
		
		Join<Object, Object> cert = null;
		
		if (!StringUtils.isBlank(conditionBean.getQualificationClassId())) {
			if(cert == null )cert = entity.join("certs");
			restrictions.add(cb.isTrue(cert.<Boolean>get("valid")));
			restrictions.add(cb.isTrue(cert.<Boolean>get("auditResult")));
			Join<QualificationTemplate, QualificationClass> clazz = cert.join("qualificationClass");
			restrictions.add(cb.equal(clazz.get("id"), conditionBean.getQualificationClassId()));
		}

		if(getParameterValues().get("qClassName") != null) {
			if (!StringUtils.isBlank(getParameterValues().get("qClassName").toString())) {
				if(cert == null )cert = entity.join("certs");
				restrictions.add(cb.isTrue(cert.<Boolean>get("valid")));
				restrictions.add(cb.isTrue(cert.<Boolean>get("auditResult")));
				Join<QualificationTemplate, QualificationClass> clazz = cert.join("qualificationClass");
				restrictions.add(cb.equal(clazz.get("name"), getParameterValues().get("qClassName").toString()));
			}
		}	
		
		if (conditionBean.getCertLevel() != null) {
			Join<QualificationCert, QualificationTemplate> qt = cert.join("qualificationTemplates");
			Join<QualificationTemplate, QualificationLevel> level = qt.join("qualificationLevel");
			restrictions.add(cb.equal(level.get("value"), conditionBean.getCertLevel()));
		}
		Join<QualificationClass, Sector> sector = null;
		if (!StringUtils.isBlank(conditionBean.getSectorId()) ) {
			if(cert == null )cert = entity.join("certs");
			sector = cert.join("qualificationClass").join("rootSectors");	
			restrictions.add(cb.equal(sector.get("id"), conditionBean.getSectorId()));
		}
		if(!StringUtils.isBlank(conditionBean.getChildSectorSno())) {
			if(cert == null )cert = entity.join("certs");
			sector = cert.join("qualificationTemplates").join("sectors");
			restrictions.add(cb.like(sector.get("sno"), getStringRestriction(conditionBean.getChildSectorSno())));
		}
		
		if ( !StringUtils.isBlank( conditionBean.getAgentServiceId() ) ) {
			Join<ServiceSupplier, AgentService> agentService = entity.join( "mainBusinesses" ).join( "agentService" );
			restrictions.add( cb.equal( agentService.get( "id" ), conditionBean.getAgentServiceId() ) );
		}
		
		if(minScore != null) {
			restrictions.add(cb.greaterThanOrEqualTo(entity.get("creditScore"), minScore));
		}
		if(maxScore != null) {
			restrictions.add(cb.lessThanOrEqualTo(entity.get("creditScore"), maxScore));
		}
		if (!StringUtils.isBlank(cnname))
			restrictions.add(cb.like(entity.get("cnname"), getStringRestriction(cnname)));
		return restrictions;
	}

	@Override
	protected Order[] getOrderArray( CriteriaBuilder cb, Root<ServiceSupplier> entity ) {
		List<Order> orderList = new ArrayList<Order>();
		Date defaultDate = new Date(0L);
		String auditStatus = (String)getParameterValues().get("auditStatus");
		if(StringUtils.isNoneBlank(auditStatus)) {
			if("2".equals(auditStatus)) {
				orderList.add( cb.desc( cb.coalesce(entity.get( "createDate" ),defaultDate)) );
				setOrder("createDate desc nulls last");
			}else if ("0".equals(auditStatus)) {
				orderList.add( cb.desc( cb.coalesce(entity.get( "auditDate" ),defaultDate)) );
			}else {
				orderList.add( cb.desc( cb.coalesce(entity.get( "auditDate" ),defaultDate)) );
			}
		}else{
			orderList.add( cb.desc( cb.coalesce(entity.get( "lastUpdateDate" ),defaultDate)) );
		}

		return orderList.toArray( new Order[orderList.size()] );
	}

	private String QUERY_UNAUDIT_SUPPLIER_EQL = "SELECT  serviceSupplier FROM ServiceSupplier serviceSupplier "+
			" WHERE serviceSupplier.auditted IS NULL ORDER BY createDate DESC";
	private int MAX_SIZE = 7;		
	public List<ServiceSupplier> getUnauditSuppliers(){
		return entityManager.createQuery(QUERY_UNAUDIT_SUPPLIER_EQL).setMaxResults(MAX_SIZE).getResultList();
	}
	
	public BigDecimal getMinScore() {
		return minScore;
	}

	public void setMinScore(BigDecimal minScore) {
		this.minScore = minScore;
	}

	public BigDecimal getMaxScore() {
		return maxScore;
	}

	public void setMaxScore(BigDecimal maxScore) {
		this.maxScore = maxScore;
	}

	public String getCnname() {
		return cnname;
	}

	public void setCnname(String cnname) {
		this.cnname = cnname;
	}


	public String getSeqNo() {
		return seqNo;
	}

	public void setSeqNo(String seqNo) {		
		this.seqNo = seqNo;
	}


}
